package com.ifengchao.service.impl;

import com.ifengchao.commonUtil.ServiceException;
import com.ifengchao.dao.iface.DealActAccountDao;
import com.ifengchao.service.DealActAccountService;
import com.ifengchao.util.zzy.ZhiZiYunUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单处理
 * @author chen
 *
 */
@Service
public class DealAcctServiceImpl implements DealActAccountService {

	private static final Logger logger = Logger.getLogger(DealAcctServiceImpl.class);

	@Autowired(required=true)
	private DealActAccountDao dealActAccountDao;

	/**
	 * 更新账户余额
	 */
	@Override
	public void dealActAccount() throws ServiceException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar now = Calendar.getInstance();
		now.add(Calendar.DAY_OF_MONTH, -1);
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("starttime",sdf.format(now.getTime()));
		paramMap.put("endtime",sdf.format(now.getTime()));
		JSONObject adResult = new JSONObject();
		try {
			adResult = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getBySite",paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用智子云接口失败，原因：",e);
		}
		if(null != adResult && (Boolean) adResult.get("status")) {
			List<String> plList = new ArrayList<>();
			JSONObject planObj = adResult.getJSONObject("response");
			Iterator it = planObj.keySet().iterator();
			while (it.hasNext()) {
				String key = (String)it.next();
				JSONArray dataArray = planObj.getJSONArray(key);
				if(dataArray.size()>0)
					plList.add(key);
			}
			for(int i =0;i<plList.size();i++) {
				JSONArray adArr = planObj.getJSONArray(plList.get(i));
				JSONObject obj = adArr.getJSONObject(0);
				String advertiserid = obj.getString("advertiserid");//获取广告主id
				String totalCost = obj.getString("totalCost");//获取实际花费
				String statDate = obj.getString("statDate");//获取实际花费
				// 根据智子云广告主id或者本地广告主
				Map<String,Object> adveterMap = dealActAccountDao.queryAdveterId(advertiserid);
				if(null == adveterMap || "".equals(adveterMap.get("adveterId"))) {
					logger.error("该广告主不存在！智子云广告主id："+advertiserid);
					continue;
				}
				Map<String,Object> amountParam = new HashMap<>();
				amountParam.put("adveterId",adveterMap.get("adveterId"));
				amountParam.put("serviceFee",adveterMap.get("serviceFee"));
				amountParam.put("totalCost",totalCost);
				amountParam.put("statDate",statDate);

				// 根据广告主id查询智子云订单表当天花费
				String orderAmount = dealActAccountDao.queryOrderAmount(String.valueOf(adveterMap.get("adveterId")));
				if("totalCost".equals(orderAmount)) {
					// 更新广告主冻结金额
					dealActAccountDao.upAccountAmount(amountParam);
				} else {
					amountParam.put("orderAmount",orderAmount);
					dealActAccountDao.insertErrorAmount(amountParam);
				}
			}
		}
	}
}
